import time
import json
import requests
import threading
from util import path


class AgentInfo:
    def __init__(self, agent_link):
        self.agent_info = {}
        self.agent_name = agent_link
        self.agent_link = agent_link
        self.agent_scope = "api_scope"
        self.agent_single_str = "api_single_str"
        self.agent_type = "api_type"
        self.agent_params = {}
        self.agent_icon = ""

    def __repr__(self):
        return self.agent_name

    def heart_check(self):
        for _ in range(3):  # 死循环，监听服务启动情况，启动成功后跳出
            try:
                res = requests.post(url=self.agent_link.rstrip('/') + "/heart")
                if res.status_code == 200:
                    return True
            except Exception as e:
                return False
            return False

    def load_info(self):
        print("加载agent信息，", self.agent_link)
        r = requests.post(self.agent_link.rstrip('/') + "/get_info")
        self.agent_info.update(json.loads(r.text).get("data"))
        self.agent_name = self.agent_info.get("api_name")
        self.agent_scope = self.agent_info.get("api_scope")
        self.agent_single_str = self.agent_info.get("api_single_str")
        self.agent_type = self.agent_info.get("api_type")
        self.agent_params = self.agent_info.get("api_params")
        self.agent_icon = self.agent_info.get("api_icon")
        return True

    def get_info(self):
        return {"agent_name": self.agent_name, "agent_link": self.agent_link, "agent_scope": self.agent_scope,
                "agent_single_str": self.agent_single_str, "agent_type": self.agent_type,
                "agent_params": self.agent_params, "agent_icon": self.agent_icon}


class AgentManage:
    def __init__(self):
        self.agent_info = {}
        self.threading_heart_check = None
        self.agent_heart_check()

    # def __repr__(self):
    #     return "Agent管理器"

    def register_by_link(self, agent_link):
        try:
            a_i = AgentInfo(agent_link)
            a_i.load_info()
            self.pop_by_agent_link(a_i.get_info().get("agent_link"))  # 依据agent_link进行去重
            agent_key = "agent_" + path.get_time_stamp_random()
            self.agent_info[agent_key] = a_i
            return agent_key
        except Exception as e:
            print("error in AgentManage.register_by_link", e)
            return "agent_error"

    def agent_heart(self):
        print("加载Agent心跳检测")
        while True:
            time.sleep(2)
            agent_info = dict(self.agent_info.items())
            for agent_key, agent_obj in agent_info.items():
                if not agent_obj.heart_check():
                    print(agent_obj.agent_name, "已失效！")
                    self.agent_info.pop(agent_key, None)

    def pop_by_agent_link(self, agent_link):
        agent_info = dict(self.agent_info.items())
        for agent_key, agent_obj in agent_info.items():
            if agent_obj.agent_link == agent_link:
                self.agent_info.pop(agent_key, None)

    def agent_heart_check(self):
        if not self.threading_heart_check:
            print(dir(self))
            self.threading_heart_check = threading.Thread(target=self.agent_heart)
            self.threading_heart_check.start()

    def get_agent_info_all(self):
        agent_info_all = {}
        for agent_key, agent_obj in self.agent_info.items():
            agent_info_all[agent_key] = agent_obj.get_info()
        return agent_info_all

    def get_agent_info_one(self, agent_key):
        try:
            return self.agent_info.get(agent_key).get_info()
        except Exception as e:
            print("error in AgentManage.get_agent_info_one", e)
            return {}
